#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>

using namespace std;

int main(int argc, char **argv)
{
  MYSQL *conn;
  MYSQL_RES *result;
  MYSQL_ROW row;
  int rows, num_field;
  MYSQL_FIELD *field;
  int i;
  char sqlstr[256];
  conn = mysql_init(NULL);
  mysql_real_connect(conn, "localhost", "root", "123456", "test", 0, NULL, 0);
#if 0
  mysql_query(conn, "select * from student");
  result = mysql_store_result(conn);
  num_fields = mysql_num_fields(result);
  while ((row = mysql_fetch_row(result)))
  {
      for(i = 0; i < num_fields; i++)
      {
          printf("%s ", row[i] ? row[i] : "NULL");
      }
      printf("\n");
  }
  mysql_free_result(result);
#endif
  // insert data
#if 0
  scanf("%d", &i);
  while (i) {
    memset(sqlstr, 0, sizeof(sqlstr));
    snprintf(sqlstr, sizeof(sqlstr)-1,"insert into stu_acc_tb(id, pwd) values(%d, 'li%d');", i, i);
    mysql_query(conn, sqlstr);

    memset(sqlstr, 0, sizeof(sqlstr));
    snprintf(sqlstr, sizeof(sqlstr)-1,"insert into stu_detail_tb(id ,name, age) values(%d, 'li%d', %d);", i, i, i);
    mysql_query(conn, sqlstr);
    memset(sqlstr, 0, sizeof(sqlstr));
    snprintf(sqlstr, sizeof(sqlstr)-1,"insert into stu_score_tb(id, chinese) values(%d, '%d');", i, rand()%100);
    mysql_query(conn, sqlstr);
    i--;
  }
#endif
  {
    int ret;
    ret = mysql_query(conn, "call GETMAXTIME()");
    if (ret == 0) { //  get result
        result = mysql_store_result(conn);
        if (!result)
            cout << "get result error!" << endl;
    } else {
        cout << "query error!" << endl;
    }
  }

  if (result) {
      num_field = mysql_num_fields(result);
      rows = (int)mysql_num_rows(result);
      // show title
    for (int j = 0; j < num_field; j++) {
        field = mysql_fetch_field_direct(result, j);
        if (field)
            cout << field->name << "\t\t";
    }
      cout << endl;
      // show each rows
      while ((row = mysql_fetch_row(result))) {
            for (int i = 0; i < rows; i++) {
                cout << row[i] << "\t\t";
            }
            cout << endl;
        }
  }

  mysql_close(conn);
}
